package cn.zifangsky.tree.binarytree.questions;

import org.junit.Test;

import cn.zifangsky.queue.LinkQueue;
import cn.zifangsky.tree.binarytree.BinaryTreeNode;

/**
 * 判断是否存在路径的数值和等于给定值
 * @author zifangsky
 *
 */
public class Question14 {

	/**
	 * 判断是否存在路径的数值和等于给定值
	 * 
	 * @时间复杂度 O(n)
	 * @param root
	 * @return
	 */
	public boolean checkPathSum(BinaryTreeNode<Integer> root,int sum){
		if(root == null){
			return false;
		}
		
		return checkPathSumByPreOrder(root,sum);

	}
	
	public boolean checkPathSumByPreOrder(BinaryTreeNode<Integer> root,int sum){
		if(root == null){
			return false;
		}
		
		int restSum = sum - root.getData().intValue(); //剩下的总和
		if(restSum <= 0){
			return restSum == 0;
		}else{
			return checkPathSumByPreOrder(root.getLeft(),restSum) || checkPathSumByPreOrder(root.getRight(),restSum);
		}
	}
	

	/**
	 * 测试用例
	 */
	@Test
	public void testMethods(){
		/**
		 * 使用队列构造一个供测试使用的二叉树
		 *     1
		 *   2    3
		 * 4  5  6  7
		 *   8 9  
		 */
		LinkQueue<BinaryTreeNode<Integer>> queue = new LinkQueue<BinaryTreeNode<Integer>>();
		BinaryTreeNode<Integer> root = new BinaryTreeNode<>(1); //根节点
		
		queue.push(root);
		BinaryTreeNode<Integer> temp = null;
		for(int i=2;i<10;i=i+2){
			BinaryTreeNode<Integer> tmpNode1 = new BinaryTreeNode<>(i);
			BinaryTreeNode<Integer> tmpNode2 = new BinaryTreeNode<>(i+1);
			
			temp = queue.pop();
			
			temp.setLeft(tmpNode1);
			temp.setRight(tmpNode2);
			
			if(i != 4)
				queue.push(tmpNode1);
			queue.push(tmpNode2);
		}

		System.out.println(checkPathSum(root,3)); //1 -> 2
		System.out.println(checkPathSum(root,9)); //false
		System.out.println(checkPathSum(root,10)); //1 -> 3 -> 6
		System.out.println(checkPathSum(root,16)); //1 -> 2 -> 5 -> 8
		
	}

}
